<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物资保养</title>
    <link rel="stylesheet" href="/css/elementui/index.css">
    <link rel="stylesheet" href="/css/exam/css/style.css">
    <link rel="stylesheet" href="/iconfont/iconfont.css">
    <script src="/css/exam/js/httpVueLoader.js"></script>
</head>

<body>
    <div id="app">
        <!--导航切换-->
        <div class=".p-30">
            {{ csrf_field() }}
            <el-card>
                <el-form label-width="100px" :model="formInline" :rules="rules" ref="increase">
                    <el-row>
                        <p>保养清单添加</p>
                    </el-row>
                    <el-row type="flex">
                        <el-form-item label="所属单位" prop="name">
                            <el-select v-model="formInline.name" placeholder="请选择所属单位" @change="unitChangeHandler"
                                style="width:180px">
                                <el-option v-for="(value, key, index) in get_warehouse_type" :key="value.id"
                                    :label="value.name" :value="value.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="单位名称" prop="incident">
                            <el-select v-model="formInline.incident" placeholder="请选择单位名称" @change="unit_list($event)"
                                style="width:180px" filterable>
                                <el-option v-for="(value, key, index) in goodsdata" :key="value.id"
                                    :label="value.comName" :value="value.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="保养人" prop="applicant">
                            <el-select v-model="formInline.applicant" placeholder="请选择保养人" filterable @change="avenue"
                                style="width:180px">
                                <el-option v-for="(value, key, index) in personnel_list" :key="value.id"
                                    :label="value.name" :value="value.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label-width="50px">
                            <el-button type="primary" @click='add_details'>添加明细</el-button>
                        </el-form-item>
                    </el-row>

                </el-form>
            </el-card>
            <!-- 弹窗 -->
            <el-dialog title="物资详情" :visible.sync="dialogVisible" width="90%">
                <el-form :model="equipment_tools" ref="verification" label-width="10px">
                    <el-row type="flex">
                        <el-form-item prop="classification_name">

                            <!-- <el-select v-model="equipment_tools.classification_name" placeholder="请选择分类名称"
                                style="width:180px" @change="ChangeGoods">
                                <el-option v-for="(item, index) in process" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select> -->

                              <el-cascader
                              v-model="equipment_tools.classification_name"
                              placeholder="请选择分类名称"
                             :options="process"
							 :props="{label:'name',value:'id'}"
                              >
                              </el-cascader>


                        </el-form-item>
                        <el-form-item prop="materials">
<!-- 
                            <el-select v-model="equipment_tools.materials" placeholder="请选择物资名称" style="width:180px"
                                filterable>
                                <el-option v-for="(item,key,index) in materialList" :key="item.id" :label="item.name"
                                    :value="item.name">
                                </el-option>
                            </el-select> -->
                           <el-input v-model="equipment_tools.materials" style="width:150px" placeholder="请输入物资名称"></el-input>  
                      

                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="primary">搜&ensp;&ensp;索</el-button>
                            <el-button @click="resetForm('verification')">重&ensp;&ensp;置</el-button>
                        </el-form-item>
                    </el-row>
                </el-form>
                <el-table border='' :data="enterprise" style="width: 100%" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="72" :selectable='selectEnable'>
                    </el-table-column>
                    <el-table-column label="序&ensp;&ensp;号" width="80" type='index' align='center'>
                    </el-table-column>
                    <el-table-column label="单位（个人）名称" prop="company.comName" width='150' align='center'>
                    </el-table-column>
                    <el-table-column label="所属单位（人）" prop="checkcategory.name" width="150" align='center'>
                    </el-table-column>
                    <el-table-column label="物资名称" prop="material_list.name" width="" align='center'>
                    </el-table-column>
                    <el-table-column label="物资分类" prop="goods.name" width="" align='center'>
                    </el-table-column>
                    <el-table-column label="具体位置" prop="seat" width="" align='center'>
                    </el-table-column>
                    <el-table-column label="联系人" prop="company.leader" width="" align='center'>
                    </el-table-column>
                    <el-table-column label="联系电话" prop="company.leaderPhone" width="" align='center'>
                    </el-table-column>
                    <el-table-column label="库存数量" prop="warehouse" width="" align='center'>
                    </el-table-column>
                    <el-table-column label="单&ensp;&ensp;位" prop="unit" width="" align='center'>
                    </el-table-column>
                </el-table>
                <div style="text-align: center">
                    <el-row style="margin-top:30px">
                        <el-col>
                            <el-button type="primary" @click="btnok">确&ensp;&ensp;定</el-button>
                            <el-button @click="btnCancel">取&ensp;&ensp;消</el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-dialog>
            <!-- 出库单添加 -->
            <div class="main">
                <div v-if="flag == 0">
                    <h3 style="text-align: center">北宅街道应急物资保养单</h3>
                    <el-form ref="formData" :model="formData">
                        <el-table style="width: 100%" border :data="formData.checkList">
                            <el-table-column label="所属单位" width="" align='center' prop="checkcategory.name">
                            </el-table-column>
                            <el-table-column label="单位名称" width="120" align='center' prop="company.comName">
                            </el-table-column>
                            <el-table-column label="序&ensp;&ensp;号" type="index" width="80" align='center'>
                            </el-table-column>
                            <el-table-column label="物资名称" width="" align='center' prop="material_list.name">
                            </el-table-column>
                            <el-table-column label="类&ensp;&ensp;别" align='center' prop="goods.name">
                            </el-table-column>
                            <el-table-column label="数&ensp;&ensp;量" width="" align='center'>
                                <template slot-scope="scope">
                                    <el-form-item :prop="'checkList.' + scope.$index + '.maintain_num'"
                                        :rules='rules1.maintain_num'>
                                        <el-input v-model.number='scope.row.maintain_num' type="number" type="number"
                                            @change='(v)=>changereqair(v,scope.row,scope.$index)'
                                            :max="scope.row.warehouse*1" :min=1></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="单&ensp;&ensp;位" width="" align='center' prop="unit">
                            </el-table-column>
                            <el-table-column label="规&ensp;&ensp;格" width="" align='center' prop="norms">
                            </el-table-column>
                            <el-table-column label="保养项目" width="" align='center'>
                                <template slot-scope="scope">
                                    <el-form-item :prop="'checkList.' + scope.$index + '.maintain_remark'"
                                        :rules='rules1.maintain_remark'>
                                        <el-input v-model='scope.row.maintain_remark'></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="操&ensp;&ensp;作" width="" align='center'>
                                <template slot-scope="scope">
                                    <el-button @click.native.prevent="deleteRow(scope.$index, formData.checkList)"
                                        type="text" size="small">
                                        删&ensp;&ensp;除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form>
                    <div style="text-align: center">
                        <el-row style="margin: 20px 0">
                            <el-col>
                                <el-button type="primary" @click="submit">确&ensp;&ensp;定</el-button>
                                <el-button type="primary" @click="cancellation">
                                    取&ensp;&ensp;消
                                </el-button>
                            </el-col>
                        </el-row>
                    </div>
                </div>
                <!-- 出库单修改 -->
                <div v-else>
                    <h3 style="text-align: center">北宅街道应急物资保养单</h3>
                    <el-form ref="formData" :model="formData" v-loading="loading">
                        <el-table style="width: 100%" border :data="editList">
                            <el-table-column label="所属单位" width="180" align='center' prop="checkcategory.name">
                            </el-table-column>
                            <el-table-column label="单位名称" width="180" align='center' prop="company.comName">
                            </el-table-column>
                            <el-table-column label="序&ensp;&ensp;号" width="80" align='center' type="index"
                                prop="check_remark">
                            </el-table-column>
                            <el-table-column label="物资名称" width="" align='center' prop="materia.name">
                            </el-table-column>
                            <el-table-column label="类&ensp;&ensp;别" width="" align='center' prop="goods.name">
                            </el-table-column>
                            <el-table-column label="数&ensp;&ensp;量" width="" align='center' prop="maintain_num">
                                <template slot-scope="scope">
                                    <el-input v-model.number='scope.row.maintain_num' type="number" type="number"
                                        @change='(v)=>changereqair1(v,scope.row,scope.$index)'
                                        :max="scope.row.warehouse*1" :min=1></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="单&ensp;&ensp;位" width="" align='center'
                                prop="warehouse_materials.unit">
                            </el-table-column>
                            <el-table-column label="规&ensp;&ensp;格" width="" align='center'
                                prop="warehouse_materials.norms">
                            </el-table-column>
                            <el-table-column label="保养项目" width="" align='center' prop="maintain_remark">
                                <template slot-scope="scope">
                                    <el-input v-model='scope.row.maintain_remark'></el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="操&ensp;&ensp;作" width="" align='center'>
                                <template slot-scope="scope">
                                    <el-button @click.native.prevent="deleteRow1(scope.$index, scope.row)" type="text"
                                        size="small">
                                        删&ensp;&ensp;除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form>
                    <div style="text-align: center">
                        <el-row style="margin: 20px 0">
                            <el-col>
                                <el-button type="primary" @click="submitall">确&ensp;&ensp;定</el-button>
                                <el-button type="primary" @click="cancellation">
                                    取&ensp;&ensp;消
                                </el-button>
                            </el-col>
                        </el-row>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script src="/css/exam/js/vue.js"></script>
    <script src="/css/elementui/index.js"></script>
    <script src="/css/exam/js/axios.min.js"></script>
    <script src="/css/exam/js/throttle.js"></script>

    <script type="module">
    const app = new Vue({
        el: '#app',
        data() {
            return {
                loading: false,
                id: '',
                unit_id: '', //单位id
                personnel_list: '', //保养人数据
                personnel_id: '', //保养人id
                dialogVisible: false,
                token: '',
                formInline: {
                    name: '',
                    incident: '',
                    applicant: ''
                },
                checkedList: [],
                deposit: [],
                enterprise: [],
                checkList: [],
                editList: [],
                process: [], //分类名称
                materialList: [],
                get_warehouse_type: [], //单位
                goodsdata: [], //单位2
                goodsdata1: [], //单位
                equipment_tools: {
                    classification_name: '',
                    materials: '',
                    unit: '',
                    classify: ''
                },
                formData: {
                    checkList: [],

                },
                // 信息列表
                information: [],
                flag: '',
                id: 1,
                rules: {
                    name: [{
                        required: true,
                        message: '请选择所属单位',
                        trigger: 'blur'
                    }],
                    incident: [{
                        required: true,
                        message: '请选择单位名称',
                        trigger: 'blur'
                    }],
                    applicant: [{
                        required: true,
                        message: '请选择保养人',
                        trigger: 'blur'
                    }, ],
                },
                rules1: {
                    maintain_num: [{
                        required: true,
                        message: '请输入保养数量',
                        trigger: 'blur'
                    }],
                    // maintain_remark:[{required:true, message: '请输入保养项目', trigger: 'blur'}],
                }

            }
        },


        created() {
            // // let id = localStorage.getItem("ids")
            // if (this.id) {
            //   // this.getEditTableList(id)
            //      let res =  localStorage.getItem(("list"))
            //      let a = JSON.parse(res)
            //      this.formInline.name = a.type
            //      this.formInline.incident = a.cause
            //      this.formInline.applicant = a.applicant
            // }
            this.getUrlKey()
            this.getEditTableList()
            this.token = '{{ csrf_token() }}'
            console.log('this.token', this.token);
            // this.classification()
            this.wuzifenlei()
            this.enterprise1()
        },
        methods: {
            //添加判断
            changereqair(val, item, index) {
                console.log(val, 'val');
                console.log(item, 'item');
                console.log(index, 'index');
                if (val * 1 > item.warehouse * 1) {
                    this.$message({
                        message: '保养数量不能大于库存数',
                        type: 'error'

                    })

                    //  this.$nextTick( ()=>{
                    //   this.checkedList[index].maintain_num = item.warehouse
                    //  })


                }

                if (val == 0) {
                    this.$message({
                        message: "保养数量不能等于0",
                        type: 'error'
                    })

                    //  this.$nextTick(()=>{
                    //    this.checkedList[index].maintain_num = 1
                    //  })

                }


            },

            changereqair1(val, item, index) {
                console.log(val);
                console.log(item);
                item.number = val * 1
                if (item.warehouse_materials && "number" in item.warehouse_materials) {
                    item.warehouse = item.warehouse_materials.number
                }
                if (val * 1 > item.warehouse * 1) {
                    console.log('大于');
                    this.$message({
                        message: '保养数量不能大于库存数',
                        type: "error"
                    })
                    //  this.$nextTick(()=>{
                    //   this.editList[index].maintain_num = item.warehouse

                    //  })

                }
                if (val == 0) {
                    this.$message({
                        message: "保养数量不能等于0",
                        type: 'error'
                    })

                    //  this.$nextTick(()=>{
                    //   this.editList[index].maintain_num = 1

                    // })

                }

            },

            //获取当前浏览器地址url中的id
            getUrlKey() {
                var url = window.location.href; //获取当前url
                var dz_url = url.split('#')[0]; //获取#/之前的字符串
                //获取?之后的参数字符串
                if (dz_url.split('?')[1] != undefined) {
                    var cs = dz_url.split('?')[1];
                    var cs_arr = cs.split('&'); //参数字符串分割为数组
                    var cs = {};
                    for (var i = 0; i < cs_arr.length; i++) { //遍历数组，拿到json对象
                        cs[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]
                    }
                    this.id = cs.id
                    this.flag = 1
                } else {
                    this.id = ''
                    this.flag = 0
                };

            },

          async wuzifenlei(){
            let res = await axios.post('/admin/goods/goodslistdata')
            this.process = res.data.data.list
            console.log('res11111111111', this.goodsdata);

            },
            //物资分类列表
            // async classification() {
            //     let res = await axios.get('/admin/goods/category')
            //     console.log('res', res);
            //     this.process = res.data.data

            // },
            //点击物资分类，物资下拉改变
            // ChangeGoods(val) {
            //     console.log(val);
            //     axios.post('/admin/materialList/material_all', {
            //             goods_id: val
            //         })
            //         .then(res => {
            //             this.materialList = res.data.data
            //         }).catch(error => {
            //             console.log('请求失败：' + error);
            //         })

            // },


            //获取企业分类
            async enterprise1() {
                let res = await axios.get('/admin/category/list')
                console.log('res', res);
                this.get_warehouse_type = res.data.data
            },
            //企业列表
            async unitChangeHandler(val) {
                this.goodsdata = []
                // let index = this.get_warehouse_type.findIndex(item => item.id == val)
                // let curType = this.get_warehouse_type[index].id
                // let res  =  await axios.get(`/admin/company/list?category=${curType}`)
                let res = await axios.post('/admin/stock/company_all', {
                    checkcategory_id: val
                })
                this.goodsdata = res.data.data
                this.formInline.incident = ''
            },
            //获取单位id
            async unit_list(val) {
                let obj = {};
                obj = this.goodsdata.find((item) => { //这里的userList就是上面遍历的数据源
                    return item.id === val; //筛选出匹配数据
                });
                console.log(val); //获取的 id
                // console.log(obj.comName);//获取的 name
                // let a = 7
                let res = await axios.get(`/admin/user/list?company_id=${val}`)
                this.personnel_list = res.data.data
            },
            //获取人员id     
            async avenue(val) {
                // let obj1 = {};
                //   obj1 = this.personnel_list.find((item)=>{//这里的userList就是上面遍历的数据源
                //       return item.id === val;//筛选出匹配数据
                //   });
                console.log(val); //获取的 id
                this.personnel_id = val
            },
            //重置
            resetForm(formName) {
                this.$refs[formName].resetFields()
                this.primary()
            },
            //   //保养人
            //   async personnel(){
            //     let a = localStorage.getItem(("company_id"))
            //    let res = await axios.get('/admin/user/list',{
            //     params:{
            //       company_id:a
            //      }
            //    })
            //    console.log('aaaaa',res);
            //    res.data.data.forEach( a =>{
            //     console.log(a.name);
            //     this.formInline.applicant = a.name
            //    })
            //    console.log('111111', res.data.data);
            // },
            //回显
            async getEditTableList() {
                let maintain_number = localStorage.getItem("maintain_number")
                console.log('maintain_number', maintain_number);
                let res = await axios.get('/admin/maintain/data', {
                    params: {
                        maintain_number,
                    }

                })
                this.editList = res.data.data
                //这里回显拿的
                if (this.id) {
                    const {
                        company,
                        checkcategory: category,
                        users
                    } = this.editList[0]

                    await this.unitChangeHandler(category.id)
                    await this.unit_list(company.id)
                    await this.avenue(users.id)

                    setTimeout(() => {
                        this.formInline.name = category.id
                        this.formInline.incident = company.id
                        this.formInline.applicant = users.id
                    }, 1000);
                }
                // // localStorage.removeItem("ids")
                // this.editList.push(res.data.data)
                // console.log(res.data.data.get_outbound_type,'this.editList');
                // this.get_warehouse_type = res.data.data.get_outbound_type
            },
            //打开弹窗
            async add_details() {
                try {
                    this.getEditTableList()
                    await this.$refs.increase.validate()
                    this.dialogVisible = true
                    let res = await axios.get('/admin/goods/list', {
                        params: {
                            checkcategory_id: this.formInline.name,
                            company_id: this.formInline.incident
                        }
                    })
                    this.enterprise = res.data.data
                } catch (error) {
                    console.log(error);
                }
            },
            //搜索物资信息
            async primary() {

               var a = this.equipment_tools.classification_name.toString()
               let array = a.split(',')
               let last = array[array.length-1]
               console.log(last,'last');

                try {
                    await this.$refs.verification.validate()
                    let res = await axios.get('/admin/goods/list', {
                        params: {
                            goods_id:last,
                            name: this.equipment_tools.materials,
                            checkcategory_id: this.formInline.name,
                            company_id: this.formInline.incident
                        }


                    })
                    let data = res.data.data
                    this.enterprise = data
                } catch (error) {
                    console.log('请求失败：' + error);
                }
            },
            //列表为0，禁选
            selectEnable(row) {
                if (row.warehouse !== 0) {
                    return true
                }
            },
            //添加明细
            async btnok() {
                let checked = []
                console.log('this.editList111', this.editList);
                this.checkedList.forEach(item => {
                    item.warehouse_materials_id = item.id,
                        item.isAdd = true
                })

                if (!this.id) {
                    if (this.formData.checkList.length > 0) {
                        let toAdd1 = this.deposit.filter(checkItem => !this.formData.checkList.some(item =>
                            item.company.comName === checkItem.company.comName && item.material_list
                            .name === checkItem.material_list.name))
                        if (toAdd1.length > 0) {
                            this.formData.checkList = [...this.formData.checkList, ...toAdd1]
                        }
                    } else {
                        console.log('2');
                        this.formData.checkList = this.formData.checkList.concat(this.deposit)
                    }
                    this.dialogVisible = false
                }

                //修改的 
                if (this.id) {
                    this.checkedList.forEach(item => {

                        item.materia = item.material_list

                    })
                    if (this.editList) {
                        console.log('editList', this.editList)
                        console.log('checkedList1111111111', this.checkedList);
                        let toAdd = this.checkedList.filter(checkItem => !this.editList.some(item => item
                            .company.comName === checkItem.company.comName && item.materia.name ===
                            checkItem.materia.name))

                        if (toAdd.length > 0) {
                            console.log('toAdd', toAdd);
                            this.editList = [...this.editList, ...toAdd]
                        }
                    } else {
                        console.log('2');
                        this.editList = this.editList.concat(this.checkedList)
                    }
                    this.dialogVisible = false
                }
            },

            //勾选列表
            handleSelectionChange(val) {
                // this.formData.checkList = val
                // this.editList = val
                // console.log(this.formData.checkList,275);
                // console.log(this.editList,1111111);
                this.checkedList = val
                this.deposit = val
            },

            //关闭弹窗
            btnCancel() {
                this.dialogVisible = false
            },
            // 添加
            submit: throttle(async function(event) {
                //添加判断库存
                if (this.formData.checkList.some(item => (item.maintain_num > item.warehouse) ||
                        item.maintain_num == 0)) {
                    return
                }
                await this.$refs.increase.validate()
                await this.$refs.formData.validate()
                let check_data = []
                this.formData.checkList.forEach(element => {
                    check_data.push({
                        maintain_remark: element.maintain_remark,
                        maintain_num: element.maintain_num,
                        warehouse_materials_id: element.id,
                    })

                })
                let param = {
                    _token: this.token,
                    check_data: check_data,
                    user_id: this.personnel_id

                }

                axios.post('/admin/maintain/edit', param).then(res => {
                    console.log(res, 306);
                    if (res.data.code == 0) {
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        });
                        this.formData.checkList = []
                        window.location.href = "/admin/warehouse/maintainview"
                    } else {
                        this.$message("保存失败！")
                    }

                })
            }, 2000),
            //删除行
            deleteRow(index, rows) {
                console.log('rows', rows);
                rows.splice(index, 1);
                // console.log('#',this.allarr)
                // console.log('index',index);
                // console.log(rows);
            },
            //删除行
            async deleteRow1(index, rows) {
                let res = await axios.get('/admin/maintain/delete', {
                    params: {
                        id: rows.id
                    }

                })
                if (res.data.code == 200) {
                    this.$message({
                        message: '删除成功',
                        type: 'success'
                    })

                    this.getEditTableList()

                }

            },
            //取消返  回上一页
            cancellation() {

                window.location.href = "/admin/warehouse/maintainview"

            },
            //修改
            submitall: throttle(async function(event) {
                this.loading = true
                //修改判断库存
                this.editList.forEach(ele => {
                    if (ele.warehouse_materials) {
                        ele.warehouse = ele.warehouse_materials.number
                    }
                    console.log(ele);
                })
                if (this.editList.some(item => (item.maintain_num > item.warehouse) || item
                        .maintain_num == 0)) {
                    this.loading = false
                    return

                }
                await this.$refs.increase.validate()
                let check_data = []
                console.log('this.editList', this.editList);
                this.editList.forEach(element => {
                    if (element.isAdd) {
                        check_data.push({
                            maintain_remark: element.maintain_remark || '',
                            maintain_num: element.maintain_num || '',
                            warehouse_materials_id: element.warehouse_materials_id
                        })
                    } else {
                        check_data.push({
                            maintain_remark: element.maintain_remark,
                            maintain_num: element.maintain_num,
                            id: element.id
                        })
                    }
                })
                console.log('sdsadada', check_data);
                let param = {
                    _token: this.token,
                    check_data: check_data,
                    user_id: this.personnel_id
                }
                axios.post('/admin/maintain/edit', param).then(res => {
                    if (res.data.code == 0) {
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        });
                        this.formData.checkList = []
                        window.location.href = "/admin/warehouse/maintainview"
                    } else {
                        this.$message("保存失败！")

                    }
                    this.loading = false
                })

            }, 2000),
        }

    })
    </script>
    <style scoped>
    .el-table .el-table__cell:first-child {
        text-align: center;
    }

    .el-divider {
        margin: 0;
    }
    </style>
</body>

</html>